<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var fourSum = function (nums, target) {
      if (nums.length < 4) return []

      nums.sort((a, b) => a - b)

      const res = []

      // -3是因为i后面的剩余元素最少是3个
      for (let i = 0, max = nums.length - 3, endIndex = nums.length - 1; i < max; i++) {
        let startPoint = i;

        // 当i为0时，starPoint取值1，循环条件：2 < endIndex
        while (++startPoint + 1 < endIndex) {
          let nextPoint = startPoint
          let endPoint = endIndex

          while (++nextPoint < endPoint) {
            const sum = nums[i] + nums[startPoint] + nums[nextPoint] + nums[endPoint]

            if (sum === target) {
              res.push([nums[i], nums[startPoint], nums[nextPoint], nums[endPoint]])

              // 剪枝
              while (nums[nextPoint] === nums[nextPoint + 1]) nextPoint++

            } else if (sum > target) {
              endPoint--
              nextPoint--
            }
          }
          // 剪枝
          while (nums[startPoint] === nums[startPoint + 1]) startPoint++
        }
        // 剪枝
        while (nums[i] === nums[i + 1]) i++
      }
      return res
    }
    console.log(fourSum([1, 0, -1, 0, -2, 2], 0))
  </script>
</body>

</html>